package com.kly.utils;

import org.springframework.data.redis.core.StringRedisTemplate;

import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;

/**
 * 全局id生成器
 * @author admin
 * @date 2025/4/6
 */
public class IdWorker {


    /**
     * 开始时间戳
     */
    private static final long BEGIN_TIMESTAMP = 1743947365L;
    /**
     * 位数
     */
    private static final long COUNT_BITS = 32;

    private final StringRedisTemplate stringRedisTemplate;

    public IdWorker(StringRedisTemplate stringRedisTemplate) {
        this.stringRedisTemplate = stringRedisTemplate;
    }


    /**
     * 生成全局唯一id
     * @param prefix
     * @return
     */
    public long nextId(String prefix) {
        LocalDateTime now = LocalDateTime.now();
        long epochSecond = now.toEpochSecond(ZoneOffset.UTC);
        long timestamp = epochSecond - BEGIN_TIMESTAMP;
        // 当前日期
        String date = now.format(DateTimeFormatter.ofPattern("yyyy:MM:dd"));
        // 获取自增值
        String key = String.format("icr:%s:%s", prefix, date);
        long increment = stringRedisTemplate.opsForValue().increment(key);
        // 返回id
        return timestamp << COUNT_BITS | increment;
    }

}
